package main

import (
	"bytes"
	"context"
	"os"

	"gitee.com/doraemon1996/bunny/log"
	"gitee.com/doraemon1996/bunny/structure"
)

type LogHook struct {
	structure.Control

	file      *os.File
	formatter *log.TextFormatter
}

func (lh *LogHook) Levels() []log.Level {
	return log.AllLevels
}

func (lh *LogHook) Fire(entry *log.Entry) {
	if lh.file == nil {
		return
	}

	buf := new(bytes.Buffer)
	lh.formatter.Format(entry, buf)
	lh.file.Write(buf.Bytes())
}

func FileLog(filePath string, logLevel string) {
	if logLevel != "" {
		if level, err := log.ParseLevel(logLevel); err == nil {
			log.SetLevel(level)
		}
	}

	if filePath == "" {
		return
	}

	file, err := os.OpenFile(filePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		log.Fatalf("open log file with path %s failed. err: %v", filePath, err)
	}

	hook := new(LogHook)
	hook.Init(context.Background(), nil)
	hook.Start(func() {
		hook.file = file
		hook.formatter = new(log.TextFormatter)
	})

	log.ExitHandlerAppend(func() {
		hook.Stop(func() {
			if hook.file != nil {
				hook.file.Close()
			}
		})
	})

	log.AddHook(hook)
}
